package com.sntk.organauthomanager.application.controller;

import com.sntk.organauthomanager.application.dto.ResponseData;
import com.sntk.organauthomanager.infrastructure.exception.DefinedException;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: GlobalExceptionHandler
 * @author: wgchao
 * @createTime: 2019/9/3 11:12 AM
 * @Description: 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ExpiredJwtException.class)
    public ResponseData exceptionHandler(HttpServletRequest request, ExpiredJwtException exception) throws Exception {
        return handleErrorInfo(request, "凭证已过期，请重新登陆", "908", exception);
    }

    @ExceptionHandler(ClassCastException.class)
    public ResponseData exceptionHandler(HttpServletRequest request, ClassCastException exception) throws Exception {
        return handleErrorInfo(request, "信息正在被其他人操作", "1099", exception);
    }

    @ExceptionHandler(DefinedException.class)
    public ResponseData exceptionHandler(HttpServletRequest request, DefinedException exception) throws Exception {
        return handleErrorInfo(request, exception.getMessage(), exception.getCode(), exception);
    }

    @ExceptionHandler(Exception.class)
    public ResponseData exceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
        return handleErrorInfo(request, exception.getMessage(), "999", exception);
    }

    private ResponseData<String> handleErrorInfo(HttpServletRequest request, String message, String code, Exception exception) {
        exception.printStackTrace();
        return ResponseData.error(code, message);
    }
}
